import sys
import os
import json
import tkinter as tk
from tkinter import messagebox


def format_duration(seconds):
    """将秒数转换为可读的时长格式"""
    mins, secs = divmod(int(seconds), 60)
    hours, mins = divmod(mins, 60)
    if hours > 0:
        return f"{hours}:{mins:02d}:{secs:02d}"
    else:
        return f"{mins:02d}:{secs:02d}"


def play_audio_file(file_path):
    """根据设置使用系统默认播放器或自定义播放器播放音频文件"""
    try:
        # 读取设置文件
        settings_file = 'settings.json'
        settings = {}
        
        if os.path.exists(settings_file):
            with open(settings_file, 'r', encoding='utf-8') as f:
                settings = json.load(f)
        
        # 获取播放器设置
        player_settings = settings.get('player', {})
        default_player = player_settings.get('default_player', '系统默认')
        
        # 根据设置选择播放器
        if default_player == '自定义':
            # 使用自定义播放器
            custom_player_path = player_settings.get('path', '')
            
            if custom_player_path and os.path.exists(custom_player_path):
                import subprocess
                subprocess.Popen([custom_player_path, file_path], shell=True)
            else:
                messagebox.showerror("错误", "自定义播放器路径不存在或为空，请重新设置")
        else:
            # 使用系统默认播放器
            if os.name == 'nt':  # Windows
                os.startfile(file_path)
            else:  # macOS, Linux 等
                opener = 'open' if sys.platform == 'darwin' else 'xdg-open'
                subprocess.run([opener, file_path])
        
        return True
    except Exception as e:
        messagebox.showerror("错误", f"无法播放歌曲: {str(e)}")
        return False


def get_file_info(file_path):
    """获取文件的基本信息"""
    if os.path.exists(file_path):
        stats = os.stat(file_path)
        return {
            'size': stats.st_size,
            'modified_time': stats.st_mtime
        }
    return None


def search_song_in_list(songs, search_text):
    """在歌曲列表中搜索匹配的歌曲"""
    search_text = search_text.lower()
    for i, song in enumerate(songs):
        if (search_text in song['filename'].lower() or \
            search_text in song['artist'].lower() or \
            search_text in song['title'].lower()):
            return i  # 返回找到的歌曲索引
    return -1  # 未找到匹配的歌曲